package org.linlinjava.litemall.db.service;

import org.linlinjava.litemall.db.domain.LitemallCoupon;
import org.linlinjava.litemall.db.domain.LitemallCouponUser;
import org.linlinjava.litemall.db.util.CouponConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class CouponVerifyService {

    @Autowired
    private LitemallCouponUserService couponUserService;
    @Autowired
    private LitemallCouponService couponService;

    /**
     * 检测优惠券是否合法
     * @author Riko
     * @date 2019/11/23
     * @update 2019/11/23
     **/
    public LitemallCoupon checkCoupon(Integer userId, Integer userCouponId, BigDecimal totalPrice) {
        LitemallCouponUser couponUser = couponUserService.findById(userCouponId);
        if (couponUser == null) {
            return null;
        }
        LitemallCoupon coupon = couponService.findById(couponUser.getCouponId());

        // 检查是否超期
        Short timeType = coupon.getTimeType();
        Short days = coupon.getDays();
        LocalDateTime now = LocalDateTime.now();
        if (timeType.equals(CouponConstant.TIME_TYPE_TIME)) {
            if (now.isBefore(coupon.getStartTime()) || now.isAfter(coupon.getEndTime())) {
                return null;
            }
        }
        else if(timeType.equals(CouponConstant.TIME_TYPE_DAYS)) {
            LocalDateTime expired = couponUser.getAddTime().plusDays(days);
            if (now.isAfter(expired)) {
                return null;
            }
        }
        else {
            return null;
        }

        boolean condition1 = !couponUser.getDeleted();
        boolean condition2 = couponUser.getStatus().equals(CouponConstant.STATUS_NORMAL);
        boolean condition3 = couponUser.getUserId().equals(userId);
        boolean condition4 = coupon.getMin().compareTo(totalPrice) < 0;
        if (condition1 && condition2 && condition3 && condition4) {
            return coupon;
        }
        return null;
    }

}